
//
//  SolveInfo.m
//  big
//
//  Created by Ios on 17/6/6.
//  Copyright © 2017年 Ios. All rights reserved.
//

#import "MBSolveInfo.h"
//#import <YYAnimatedImageView.h>
#import <YYFrameImage.h>
#import "KYBarrageKit.h"
#import "ViewController.h"


@interface MBSolveInfo ()
{
    NSTimeInterval timerInterval;
}


//wirteBy--MB_lee
@property(nonatomic,weak)NSTimer *timer;
@property(nonatomic,strong)NSThread *MB_thread;
@property(nonatomic,strong)NSLock *lock;
@property(nonatomic,strong)NSMutableDictionary *dict;

@property(nonatomic,weak)UIViewController *viewcontroller;  // 控制器已经强引用次对象；所以内部要使用弱引用；
@property(nonatomic,assign)BOOL isBegan; //第一次进入代理方法判定
@property(nonatomic,strong)NSString *animationName; //记录数组第一位的数据（每次第一个数据都是原来的第二个数据）
@property(nonatomic,assign)BOOL isAnimating;

@property(nonatomic,strong)UIView *vi; //模拟动画


//writeBy--LB
@property(nonatomic,strong)YYAnimatedImageView *imageview;  //保存YYAnimationImageView 的指针，查看其属性currentIsPlayingAnimation来判断是否在动画（项目卡点）
@property(nonatomic,strong)YYFrameImage *image;
@property(nonatomic,strong)KYBarrageManager *manager;

@end


@implementation MBSolveInfo

-(instancetype)init{
    if (self = [super init]) {
        //添加数组，创建线程，开启定时器
        [self mut];
        [self creatMB_thread];
        _isAnimating = NO;
    }
    return  self;
}

//播放动画的数据
-(NSMutableDictionary *)dict{
    if (!_dict) {
       NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:4];
        dict[@"lv"] = @"lv";
        dict[@"pc"]  = @"pc";
        dict[@"hc"] = @"hc";
        dict[@"yl"] = @"yl";
        _dict = dict;
    }
    return  _dict;
    
    
}
//线程锁
-(NSLock *)lock{
    if (!_lock) {
        _lock = [[NSLock alloc]init];
    }
    return  _lock;
}
//初始化数组
-(NSMutableArray *)mut{
    if (!_mut) {
        _mut = [NSMutableArray array];
    }
    return _mut;
}


//创建常驻线程

-(void)creatMB_thread{
   
    _MB_thread = [[NSThread alloc]initWithTarget:self selector:@selector(run) object:nil];
    [_MB_thread start];
    
  
}
//生成定时器
-(NSTimer *)timer{
    if (!_timer) {
        
        _timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(MBsolveInfo) userInfo:nil repeats:YES];
    }
    return  _timer;
}

//在子线程中执行

-(void)run{
    [self timer];
    [[NSRunLoop currentRunLoop] addPort:[NSPort port] forMode:NSDefaultRunLoopMode];
    [[NSRunLoop currentRunLoop] run];

}

//在常驻线程中执行
-(void)MBsolveInfo{
   [self.lock lock];
            if (!_isAnimating) {
         
                if (self.mut.count) { //数组里面有数据，才去取
                    _isAnimating = YES;
                  
                    _animationName = self.mut.firstObject;
                    NSLog(@"取出的数据----%@",_animationName);
                    NSLog(@"现有数据个数1-----------%ld",self.mut.count);
                    [self.mut removeObjectAtIndex:0];
                     NSLog(@"现有数据个数2-----------%ld",self.mut.count);
                    // ----------if else 语句
                    if ([_animationName isEqualToString:@"lv"]) {
                        [self showAnimation:_animationName imageCount:37 viewcontroller:_viewcontroller];
                    }else if ([_animationName isEqualToString:@"pc"]){
                        [self showAnimation:_animationName imageCount:70 viewcontroller:_viewcontroller];
                    }else if ([_animationName isEqualToString:@"hc"]){
                        [self showAnimation:_animationName imageCount:60 viewcontroller:_viewcontroller];
                    }else if ([_animationName isEqualToString:@"yl"]){
                        [self showAnimation:_animationName imageCount:80 viewcontroller:_viewcontroller];
                    }
                    //-----------
                
                }
                
            }

      [self.lock unlock];
    
    }


#pragma  mar --对外接口
-(void)showBigCustomWithName:(BigCustomeName)name viewContoller:(UIViewController *)viewcontrolle{
    //这里的操作----在主线程执行
    //判断是不是第一次触发代理方法，如果是第一次触发操作，将控制器保存，以便内部使用外部的 控制器
    if (!_isBegan) {
        _viewcontroller = viewcontrolle;
       _isBegan = YES;
    }

    
    NSString *animationName;
    switch (name) {
        case BigCustomeNameLove:
            animationName = self.dict[@"lv"];
            break;
            case BigCustomeNameTrain:
            animationName = self.dict[@"hc"];
            break;
            case BigCustomeNameSuperCar:
            animationName = self.dict[@"pc"];
            break;
            case BigCustomeNameCruisship:
            animationName = self.dict[@"yl"];
            break;
        default:
            break;
    }
//    主线程加数据
    
        [self.mut addObject:animationName];
        NSLog(@"现在数组里面有多少数据---%ld",self.mut.count);
}


#pragma  mark ----kvo 监听imageview 是否在动画，如果在动画_isAnimation = yes ，如果没有在动画 _isAnimation = NO；此方法主要是设置_isAnimation = NO//在主线程执行
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{

    [_imageview removeObserver:self forKeyPath:@"currentIsPlayingAnimation"];
    [_imageview removeFromSuperview];
    [self.vi removeFromSuperview];
    
    
    [self performSelector:@selector(setAnimatingValueAtMB_Thread) onThread:_MB_thread withObject:nil waitUntilDone:YES];

}

-(void)setAnimatingValueAtMB_Thread{
    _isAnimating = NO;
}

#pragma  mark --writeBy--FB----加载图片;(以下方法是利用第三方库YYIMage，进行的动画播放操作)
//主线程执行
-(void)showAnimation:(NSString *)imageName imageCount:(NSInteger )count viewcontroller:(UIViewController *)viewcontroller{
    //        所有图片的路径
    NSArray *paths =  [self runAnimationgWithCount:count andImangeName:imageName];
    //        每个图片对应的时间间隔
    NSArray *times = [self getImageTimesWithImageCount:count];

    
    _image = [[YYFrameImage alloc] initWithImagePaths:paths frameDurations:times loopCount:1];
    YYAnimatedImageView *imageView = [[YYAnimatedImageView alloc] initWithImage:_image];
   

    imageView.frame = viewcontroller.view.frame;
    imageView.image = _image;
    
    
#pragma mark --引用imagview 进行监听是否正在执行动画
    _imageview = imageView;
    
   dispatch_sync(dispatch_get_main_queue(), ^{
        [viewcontroller.view addSubview:imageView];
       
       [self showTanMu];
#pragma mark --弹幕
     
   });
  
    [imageView addObserver:self forKeyPath:@"currentIsPlayingAnimation" options:NSKeyValueObservingOptionNew context:nil];
}




- (NSMutableArray *)runAnimationgWithCount:(NSInteger )count andImangeName:(NSString *)imangeName{
    
    NSMutableArray *pathsArr = [NSMutableArray array];
    
    for (int index = 0; index < count; index ++) {
        
        NSString *imageN = [NSString stringWithFormat:@"%@%02d",imangeName,index];
        
        NSString *path = [[NSBundle mainBundle] pathForResource:imageN ofType:@"png"];
        
        [pathsArr addObject:path];
        
    }
    
    return pathsArr;
    // 清空数组中的图片
    
}

//每张图片的时间间隔
- (NSMutableArray *)getImageTimesWithImageCount:(NSInteger)count{
    NSMutableArray *times = [NSMutableArray array];
    for (int i = 0; i < count; i++) {
        [times addObject:@0.1];
    }
    return times;
    
}

//测试动画的view
-(UIView *)vi{
    if (!_vi) {
        UIView *vi = [[UIView alloc]initWithFrame:CGRectMake(100, 100, 300, 300)];
        vi.backgroundColor = [UIColor colorWithRed:arc4random()%256/255.0 green:arc4random()%256/255.0  blue:arc4random()%256/255.0  alpha:1.0];
        _vi = vi;
    }
    return  _vi;
    
}
-(void)creatView{
    
    [_viewcontroller.view addSubview:self.vi];
    
    [UIView animateWithDuration:1 animations:^{
        self.vi.center = _viewcontroller.view.center;
    }];
}
-(KYBarrageManager *)manager{
    
    if (!_manager) {
        //*****************  大礼物提醒弹幕     **************************//
        _manager = [KYBarrageManager manager];
        ViewController *viewcontroller = (ViewController *)_viewcontroller;
        
        _manager.bindingView = viewcontroller.FBview;
        //弹幕速度 毫秒
        _manager.scrollSpeed = 50;
        
        _manager.memoryMode = KYBarrageMemoryWarningModeHalf;
        
        //  出现方向
        _manager.scrollDirection = KYBarrageScrollDirectRightToLeft;
 
    }
    return  _manager;
    
}

-(void)setModel:(QDChatModel *)model{
    _model = model;
}
- (void)showTanMu{
    NSString *strs = [NSString stringWithFormat:@"%@ 给主播赠送了 %@",_model.nickname,_model.gift];
    NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:strs];
    
    [attr addAttribute:NSForegroundColorAttributeName value:RandomColor() range:NSMakeRange(0, strs.length)];
    
    KYBarrageModel *m = [[KYBarrageModel alloc] initWithBarrageContent:attr];
    m.displayLocation = _manager.displayLocation;
    m.direction       = _manager.scrollDirection;
    m.barrageType = KYBarrageDisplayTypeCustomView;
    
    
    
    [self.manager showBarrageWithDataSource:m];
    
}
UIColor * RandomColor() {
    float a = (arc4random() % 255) / 255.0;
    float b = (arc4random() % 255) / 255.0;
    float c = (arc4random() % 255) / 255.0;
    
    return [UIColor colorWithRed:a green:b blue:c alpha:1.0];
}





/*
需要在定时器方面进行优化的时候用

//创建定时器
- (void)setupTimer
{
    if (!_timer) {
        NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(solveInfo) userInfo:nil repeats:YES];
        _timer = timer;
        //在当前线程添加定时器
        [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];

    }
}
 
//销毁定时器
- (void)invalidateTimer
{
    [_timer invalidate];
    _timer = nil;
}

*/






@end
